package com.pzy.expiration.service;

import com.pzy.expiration.model.User;
import com.pzy.expiration.model.FoodItem;
import com.pzy.expiration.model.MedicineItem;
import com.pzy.expiration.model.DailyItem;
import com.pzy.expiration.repository.UserRepository;
import com.pzy.expiration.repository.FoodItemRepository;
import com.pzy.expiration.repository.MedicineItemRepository;
import com.pzy.expiration.repository.DailyItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private FoodItemRepository foodItemRepository;

    @Autowired
    private MedicineItemRepository medicineItemRepository;

    @Autowired
    private DailyItemRepository dailyItemRepository;

    // 注册新用户
    public User register(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);  // 密码需要加密
        return userRepository.save(user);
    }

    // 登录验证用户
    public User login(String username, String password) {
        Optional<User> user = userRepository.findByUsername(username);
        if (user.isPresent() && user.get().getPassword().equals(password)) {
            return user.get();
        }
        throw new RuntimeException("Invalid credentials");
    }

    // 获取该用户的所有食品
    public List<FoodItem> getFoodItemsForUser(User user) {
        return foodItemRepository.findByUser(user);
    }

    // 获取该用户的所有药品
    public List<MedicineItem> getMedicineItemsForUser(User user) {
        return medicineItemRepository.findByUser(user);
    }

    // 获取该用户的所有生活用品
    public List<DailyItem> getDailyItemsForUser(User user) {
        return dailyItemRepository.findByUser(user);
    }
}
